package ooday04;

/**
 * 多态的演示
 */
public class PolymorphicDemo {
    public static void main(String[] args) {
        /*
        //演示强转成功的条件：
        Animal o =new Dog("小黑",5,"黑");
        Dog g = (Dog) o;//引用o所指的对象，就是Dog类型
        Swim s = (Swim) o;//引用o所指的对象，实现了Swim接口
        //Fish f = (Fish) o;   //运行时会发生ClassCastException类型转换异常

        System.out.println(o instanceof Dog);  //true
        System.out.println(o instanceof Swim); //true
        System.out.println(o instanceof Fish); //false
        if (o instanceof Fish){  //false
            Fish f = (Fish) o;
        }
        */














        //演示向上造型（多态）的第二点应用
        Animal[]animals = new Animal[3];
        animals[0] = new Dog("小黑", 4, "黑");
        animals[1] = new Chick("小白", 3, "白");
        animals[2] = new Fish("小金", 2, "金");

        for (int i = 0;i< animals.length;i++){
            System.out.println(animals[i].name);
            animals[i].eat();
            animals[i].drink();

            if (animals[i] instanceof Dog ){
                Dog dog = (Dog) animals[i];
                dog.LookHome();
            }
            if (animals[i] instanceof Chick){
                Chick chick = (Chick) animals[i];
                chick.LayEggs();
            }
            if (animals[i] instanceof Swim){//适用于所有实现Swim接口的（会游泳的）
                Swim s =(Swim) animals[i];
                s.swim();
            }















        }













        /*
        Master master = new Master();
        Animal dog = new Dog("小黑", 4, "黑");      //Animal  可替换成Dog
        Animal chick = new Chick("小白", 3, "白");  //Animal  可替换成Chick
        Animal fish = new Fish("小金", 2, "金");    //Animal  可替换成Fish
        master.feed(dog);
        master.feed(chick);
        master.feed(fish);
        */







        /*
        Dog o1 = new Dog("小黑", 5, "黑");
        o1.eat();
        o1.swim();
        o1.drink();
        o1.LookHome();


        Animal o2 = new Dog("小黑", 5, "黑");
        o2.eat();
        o2.drink();

        Swim o3 = new Dog("小黑", 5, "黑");
        o3.swim();
       */

    }
}
